<template>
  <div class="app-container">
    <el-card style="border-radius: 10px;">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板编号" prop="templateOrder">
        <el-input
            v-model="queryParams.templateOrder"
            placeholder="请输入模板编号"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模板名称" prop="templateName">
        <el-input
            v-model="queryParams.templateName"
            placeholder="请输入模板名称"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="启用状态" prop="status">
        <el-select v-model="queryParams.enableFlag" placeholder="请选择是否启用" clearable>
          <el-option label="是" value="1"/>
          <el-option label="否" value="0"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>
    <el-card style="border-radius: 10px;margin-top: 15px">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['xm:templateInfo:add']"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['xm:templateInfo:edit']"
              >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['xm:templateInfo:remove']"
              >删除</el-button>
            </el-col>-->
      <!--      <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['xm:templateInfo:export']"
              >导出</el-button>
            </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="templateInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="模板编号" align="center" prop="templateOrder">
        <template slot-scope="scope">
          <el-button
              type="text"
              @click="handleView(scope.row)"
              v-hasPermi="['xm:templateInfo:query']"
          >{{ scope.row.templateOrder }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="模板名称" align="center" prop="templateName"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.template_info_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="启用状态" align="center" prop="enableFlag">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.enableFlag"
              :active-value="1"
              :inactive-value="0"
              @change="handleEnableChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy"/>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              v-if="scope.row.status==0"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['xm:templateInfo:edit']"
          >修改
          </el-button>
          <el-button
              v-if="scope.row.status==0"
              size="mini"
              type="text"
              icon="el-icon-success"
              @click="handleEditStatus(scope.row)"
              v-hasPermi="['xm:templateInfo:editStatus']"
          >完成
          </el-button>
          <el-button
              v-if="scope.row.status==0"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['xm:templateInfo:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />
    </el-card>
    <!-- 添加或修改模板信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="18">
            <el-form-item label="模板编号" prop="templateOrder">
              <el-input v-model="form.templateOrder" placeholder="请输入模板编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="80">
              <el-switch v-model="autoGenFlag"
                         active-color="#13ce66"
                         active-text="自动生成"
                         @change="handleAutoGenChange(autoGenFlag)" v-if="optType == 'add'">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="form.templateName" placeholder="请输入模板名称"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改模板信息对话框 -->
    <el-dialog :title="inaddtitle" :visible.sync="inaddopen" width="500px" append-to-body>
      <el-form ref="inaddform" :model="inaddform" :rules="inaddrules" label-width="80px">
        <el-form-item label="模板编号" prop="templateOrder">
          <el-input v-model="inaddform.templateOrder" placeholder="请输入模板编号"/>
        </el-form-item>
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="inaddform.templateName" placeholder="请输入模板名称"/>
        </el-form-item>
        <el-form-item label="序号" prop="sort">
          <el-input v-model="inaddform.sort" type="number" min="0" step="1" placeholder="请输入序号"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="inaddsubmitForm">确 定</el-button>
        <el-button @click="inaddcancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog :title="editTitle" :visible.sync="editOpen" width="80%" append-to-body>
      <div style="display: flex;">
        <el-card style="border-radius: 10px;width: 20%">

        <div class="head-container" style="height: 40rem;overflow-y: auto;">
          <el-tree
              :data="dataOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              default-expand-all
              @node-click="handleNodeClick"
          />
        </div>
        </el-card>
        <el-card style="border-radius: 10px;margin-left: 15px;width: 80%">
          <el-button
              v-if="!isShow"
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="inhandleAdd"
              style="margin-bottom: 10px"
              v-hasPermi="['xm:templateInfo:add']"
          >新增
          </el-button>
          <el-table v-loading="loading" :data="dataListOne" @selection-change="handleSelectionChange">
            <el-table-column label="模板编号" align="center" prop="templateOrder"/>
            <el-table-column label="模板名称" align="center" prop="templateName"/>
            <el-table-column label="排序" align="center" prop="sort"/>
            <el-table-column label="创建人" align="center" prop="createBy"/>
            <el-table-column label="创建时间" width="150px" align="center" prop="createTime"/>
            <el-table-column label="更新人" align="center" prop="updateBy"/>
            <el-table-column label="更新时间" width="150px" align="center" prop="updateTime"/>
            <el-table-column label="操作" v-if="!isShow" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="ineditHandleUpdate(scope.row)"
                    v-hasPermi="['xm:templateInfo:edit']"
                >修改
                </el-button>
                <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="inHandleDelete(scope.row)"
                    v-hasPermi="['xm:templateInfo:remove']"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
              v-show="allDataListOne.length > 0"
              :total="allDataListOne.length"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="handleStaticPagination"
          />
        </el-card>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editCancel">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listTemplateInfo,
  getTemplateInfo,
  delTemplateInfo,
  addTemplateInfo,
  updateTemplateInfo,
  changeEnableStatus,
  treeSelect,
  editStatus
} from "@/api/mes/xm/templateInfo";
import {genCode} from "@/api/system/autocode/rule";
import {getBomGl} from "@/api/mes/md/bomgl";

export default {
  name: "TemplateInfo",
  dicts: ['template_info_status'],
  data() {
    return {
      allDataListOne: [],
      dataOptions: null,
      dataList: [],
      dataListOne: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      optType: null,
      autoGenFlag: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模板信息表格数据
      templateInfoList: [],
      // 弹出层标题
      title: "",
      inaddtitle: "",
      // 是否显示弹出层
      open: false,
      inaddopen: false,
      editTitle: "",
      editOpen: false,
      isShow: false,
      nowParentId: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parentId: null,
        templateOrder: null, templateName: null, status: null,
        enableFlag: null,
        remarks: null,
        tenantId: null
      },
      // 表单参数
      form: {},
      inaddform: {},
      // 表单校验
      rules: {
        templateOrder: [
          {required: true, message: "模板编号不能为空", trigger: "blur"}
        ], templateName: [
          {required: true, message: "模板名称不能为空", trigger: "blur"}
        ],
      },
      inaddrules: {
        templateOrder: [
          {required: true, message: "模板编号不能为空", trigger: "blur"}
        ], templateName: [
          {required: true, message: "模板名称不能为空", trigger: "blur"}
        ], sort: [
          {required: true, message: "排序不能为空", trigger: "blur"}
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('XM_TEMPLATE_CODE').then(response => {
          this.form.templateOrder = response;
        });
      } else {
        this.form.templateOrder = null;
      }
    },
    /** 查询模板信息列表 */
    getList() {
      this.loading = true;
      listTemplateInfo(this.queryParams).then(response => {
        this.templateInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    inaddcancel() {
      this.inaddopen = false;
      this.inaddreset();
    },
    editCancel() {
      this.editOpen = false;
      this.inaddreset();
      this.dataOptions = [];
      this.dataList = [];
      this.dataListOne = [];
      this.allDataListOne = []
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        templateOrder: null,
        templateName: null,
        status: 0,
        enableFlag: null,
        remarks: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        tenantId: null
      };
      this.autoGenFlag = true;
      this.resetForm("form");
    },
    inaddreset() {
      this.inaddform = {
        id: null,
        templateOrder: null,
        parentId: null,
        sort: null,
        templateName: null,
        status: 0,
        enableFlag: null,
        remarks: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        tenantId: null
      };
      this.resetForm("inaddform");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.enableFlag=null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleView(row) {
      this.reset();
      const id = row.id || this.ids
      getTemplateInfo(id).then(response => {
        this.form = response.data;
        this.editOpen = true;
        if (this.form.status == 1) {
          this.isShow = true;
        } else {
          this.isShow = false;
        }
        this.nowParentId = id;
        this.getTreeSelect(id);
        this.editTitle = "查看模板信息";
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.optType = 'add';
      this.handleAutoGenChange(true);
      this.title = "添加模板信息";
    },
    /** 新增按钮操作 */
    inhandleAdd() {
      //this.inaddreset();
      this.inaddopen = true;
      this.inaddtitle = "添加模板信息";
    },
    handleEnableChange(row) {
      let text = row.enableFlag == "1" ? "启用" : "禁用";
      this.$modal.confirm('确认要"' + text + '""' + row.templateName + '"吗？').then(function () {
        return changeEnableStatus(row.id, row.enableFlag);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.enableFlag = row.enableFlag == 1 ? 0 : 1;
      });
    },

    handleEditStatus(row) {
      this.$modal.confirm('确认要提交完成吗？提交后不可修改。').then(function () {
        return editStatus(row.id, 1);
      }).then(() => {
        this.$modal.msgSuccess("提交成功");
        this.getList();
      }).catch(function () {
        this.getList();
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTemplateInfo(id).then(response => {
        this.form = response.data;
        this.editOpen = true;
        if (this.form.status == 1) {
          this.isShow = true;
        } else {
          this.isShow = false;
        }
        this.nowParentId = id;
        this.getTreeSelect(id);
        this.editTitle = "修改模板信息";
      });
    },
    ineditHandleUpdate(row) {
      this.inaddreset();
      const id = row.id || this.ids
      getTemplateInfo(id).then(response => {
        this.inaddform = response.data;
        this.inaddopen = true;
        this.inaddtitle = "修改模板信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTemplateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplateInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    inaddsubmitForm() {
      this.$refs["inaddform"].validate(valid => {
        if (valid) {
          if (this.inaddform.parentId == null || this.inaddform.parentId == "" || this.inaddform.parentId == undefined) {
            this.inaddform.parentId = this.nowParentId;
          }
          if (this.inaddform.id != null) {
            updateTemplateInfo(this.inaddform).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.inaddopen = false;
              this.getTreeSelect(this.nowParentId);
            });
          } else {
            addTemplateInfo(this.inaddform).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.inaddopen = false;
              this.getTreeSelect(this.nowParentId);
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除模板信息编号为"' + ids + '"的数据项？').then(function () {
        return delTemplateInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 删除按钮操作 */
    inHandleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除模板信息编号为"' + ids + '"的数据项？').then(function () {
        return delTemplateInfo(ids);
      }).then(() => {
        this.getTreeSelect(this.nowParentId);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('xm/templateInfo/export', {
        ...this.queryParams
      }, `templateInfo_${new Date().getTime()}.xlsx`)
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data,obj) {
      this.inaddreset();
      this.inaddform.parentId = data.id;

      this.findItemById(this.dataList, data.id);
    },
    handleStaticPagination() {
      const {pageNum, pageSize} = this.queryParams;
      const start = (pageNum - 1) * pageSize;
      const end = start + pageSize;
      this.dataListOne = this.allDataListOne.slice(start, end);
    },
    findItemById(data, targetId) {
      for (const item of data) {
        if (item.id === targetId) {
          this.allDataListOne = item.children.length>0?item.children : []; // 存储完整数据
          this.dataListOne = this.allDataListOne.slice(0, this.queryParams.pageSize); // 默认显示第一页
          return;
        }
        if (item.children && item.children.length > 0) {
          this.findItemById(item.children, targetId);
        }
      }
    },
    // 获取图纸分类树
    getTreeSelect(id) {
      treeSelect(id).then(response => {
        this.dataOptions = response.data.tree;
        this.dataList = response.data.list;
        this.findItemById(this.dataList, id);
      })
    },
  }
};
</script>
